import { GROUP } from "../config/config";
import GroupDB from "../db/GroupDB";
import getGroupMemberByGroupId from "../db/GroupMemberDB";

class Group {
    private _groupId: string;
    private _groupName: string;
    constructor(groupId: string, groupName: string) {
        this._groupId = groupId;
        this._groupName = groupName;
    }
    public static async CheckGroupIdExist(groupId: string): Promise<boolean> {
        return await GroupDB.findOne({ groupId: groupId }).then(group => !!group).catch(() => false); // !!:将object转换为boolean
    }

    public static async CheckGroupNameExist(groupName: string): Promise<boolean> {
        return await GroupDB.findOne({ groupName: groupName }).then(group => !!group).catch(() => false); // !!:将object转换为boolean
    }

    public async insertNewGroup() {
        await GroupDB.create({
            groupId: this._groupId,
            groupName: this._groupName
        })
    }

    public static async AddNewMember(groupId:string,memberId: string) {
        const GroupMemberDB = getGroupMemberByGroupId(groupId);
        await GroupMemberDB?.create({ memberId: memberId });
    }

    public static async GetGroupMember(groupId: string): Promise<Array<string>> {
        const GroupMemberDB = getGroupMemberByGroupId(groupId);
        const members = await GroupMemberDB?.find({}) ?? [];
        return members.map(member => member.memberId);
    }



    public static async getUserGroups(userId: string): Promise<Array<{ type: string, id: string, name: string }>> {
        const information: Array<{ type: string, id: string, name: string }> = [];
        // 查询所有群组
        const allGroups = await GroupDB.find({});
        
        for (const group of allGroups) {
            const members = await Group.GetGroupMember(group.groupId);
            if (members.includes(userId)) {
                information.push({ type: GROUP, id: group.groupId, name: group.groupName });
            }
        }
        return information;
    }


    public static async getName(groupId: string):Promise<string>{
        const user = await GroupDB.findOne({groupId: groupId});
        if(user === null) return "";
        return user.groupName;
    }
}

export default Group;